import wsgiref.handlers
import os
import re

from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.api import memcache

import utils

class CssStyleHandler( webapp.RequestHandler ):
   def get( self, requestedCssFilename ):
      # Retrieving 'browser_name' and 'browser_version'
      # First, check into the MemCache 
      browserDetailsDic = memcache.get(self.request.headers['User-Agent'])
      if browserDetailsDic is None:
         # If it's not found in MemCache, calculate it...
         browserDetailsDic = utils.getBrowserDetails(self.request.headers['User-Agent'])
         # ... and Store it in MemCache for the Future
         memcache.add(self.request.headers['User-Agent'], browserDetailsDic)
      
      # TODO: A good idea would be to cache the Stylesheet Rendering too
      # Loading the Template
      templatePath = os.path.join( os.path.dirname( __file__ ), 'style/' + requestedCssFilename )
      if ( os.path.exists(templatePath) ):
         # Setting Content-Type as "text/css"
         self.response.headers['Content-Type'] = 'text/css'
         # Rendering the Result
         self.response.out.write( template.render( templatePath, browserDetailsDic ) )

def main():
   # Creating a WSGI Application Handler
   application = webapp.WSGIApplication([
                                         ( '/style/([\w.-/]+\.css)$', CssStyleHandler )
                                         ], debug=True )
   # Executing the WSGI Application
   wsgiref.handlers.CGIHandler().run( application )

if __name__ == "__main__":
    main()
